package com.youhui.weixin.utils.excel;

import com.youhui.weixin.common.exception.MythException;
import com.youhui.weixin.common.info.MythExceptionList;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.Map;

/**
 * Created by https://github.com/kuangcp on 17-10-6  下午9:48
 * 反射工具类
 */
public class ReflectUtils {

    /**
     * 将map转换为实体类
     * @param map map数据 其中的数据事先就处理好了类型，所以直接强转
     * @param className 类名字
     * @return 返回实例化的对象
     * @throws MythException 加载类异常
     */
    public static Object mapToEntity(Map map, String className) throws MythException {
        Object entity;
        try {
            Class target = Class.forName(className);
            Method methods[] = target.getMethods();
            entity = target.newInstance();
            for (Method method : methods) {
                String name = method.getName();
                if (name.startsWith("set")) {
                    // 去除set，首字母小写
                    String cname = name.substring(3, name.length());
                    cname = toFirstLower(cname);
//                    System.out.println(cname);
                    Class[] params = method.getParameterTypes();
                    Class types = params[0];
                    if (map.get(cname) != null) {
                        if(types == String.class) {
                            method.invoke(entity, map.get(cname).toString());
                        }else if (types == long.class || types == Long.class) {
                            method.invoke(entity, Long.parseLong(map.get(cname).toString()));
                        }else if (types == int.class || types == Integer.class) {
                            method.invoke(entity, Integer.parseInt(map.get(cname).toString()));
                        }else if (types == Float.class || types == float.class) {
                            method.invoke(entity, Float.valueOf(map.get(cname).toString()));
                        }else if (types == Double.class || types == double.class) {
                            method.invoke(entity, Double.valueOf(map.get(cname).toString()));
                        }else if (types == Date.class) {
                            // TODO 处理反射的各个类型，以及总结出一个完善的工具类出来
                            method.invoke(entity, (Date) map.get(cname));
                        }
                    }
                }
            }
        } catch (ClassNotFoundException e) {
            throw new MythException(MythExceptionList.LOAD_CLASS_EXCEPTION, e, ReflectUtils.class);
        } catch (IllegalAccessException | InstantiationException | InvocationTargetException e) {
            throw new MythException(MythExceptionList.PARSE_TYPE_EXCEPTION, e, ReflectUtils.class);
        }
        return entity;
    }

    //首字母小写
    private static String toFirstLower(String name) {
        char[] cs=name.toCharArray();
        cs[0]+=32;
        return String.valueOf(cs);

    }
}
